<template>
    <div>
        <button type="button" class="btn btn-white btn-success btn-round"
                v-on:click="selectFile()">
            <i class="ace-icon fa fa-upload blue"></i>
            {{text}}
        </button>
        <input ref="file" class="hidden" v-bind:id="inputId+'-input'" type="file" name="file" v-on:change="uploadFile()">

    </div>
</template>

<script>
    export default {
        name: 'pagination',
        props: {
            use:{
                default:null
            },
            inputId:{
                default: "file-upload"
            },
            suffixs:{
                default:[]
            },
            text:{
                default: "上传文件"
            },
            afterUpload: {
                type: Function,
                default: null
            }
        },
        data: function () {
            return {
            }
        },
        watch: {

        },
        methods: {
            /*选择图片*/
            selectFile() {
                let _this = this;
                $("#"+_this.inputId + "-input").trigger('click');
            },
            /*上传头像*/
            uploadFile() {
                let _this = this;
                let formData = new window.FormData();
                let file = _this.$refs.file.files[0];
                //判断文件格式
                let suffixs = _this.suffixs;
                let fileName = file.name;
                let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
                let validateSuffix = false;
                for (let i = 0; i < suffixs.length; i++) {
                    if (suffixs[i].toLowerCase() == suffix) {
                        validateSuffix = true;
                        break;
                    }
                }
                if (!validateSuffix) {
                    Toast.warning("文件格式不正确!只支持格式: " + suffixs.join(","));
                    $("#"+_this.inputId + "-input").val('');
                    return;
                }
                formData.append('file', file);
                formData.append('use', _this.use);
                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/file/admin/upload', formData).then((response) => {
                    Loading.hide();
                    _this.afterUpload(response.data);
                    $("#"+_this.inputId + "-input").val('');
                });
            },

        }
    }
</script>

